package com.mymarkdown.app.util;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.mymarkdown.app.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author zenglun
 * @date 2021/12/8 9:09 上午
 * @description: TODO
 */
@Slf4j
public class TemplateHtmlUtil {

    private Cache cache;

    private static TemplateHtmlUtil self;

    private TemplateHtmlUtil() {
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }

    /**
     * 获取模板字符串,从缓存中获取字符串，如果缓存中没有则读取IO从文件中获取模板字符串
     * @return
     */
    public String getTemplateStr() {
        String html = cache.get(Constant.AllCacheKey.HTML_TEMPLATE_CACHE_KEY, String.class);
        try {
            if (StrUtil.isEmpty(html)) {
                InputStream resourceAsStream = new FileInputStream(Constant.AllFilePath.MD_HTML_TEMPLATE_FILE);
                html = IoUtil.read(resourceAsStream, StandardCharsets.UTF_8);
                cache.put(Constant.AllCacheKey.HTML_TEMPLATE_CACHE_KEY, html);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("[TemplateHtmlUtil]---[getTemplateStr],模板文件未找到,异常信息为:{}", e);
        }
        return html;
    }

    public static TemplateHtmlUtil getSelf() {
        if (self == null) {
            synchronized (TemplateHtmlUtil.class) {
                if (self == null) {
                    self = new TemplateHtmlUtil();
                }
            }
        }
        return self;
    }
}
